package cn.itlaobing.web.controller;

import cn.itlaobing.entity.Gender;
import cn.itlaobing.entity.UserEntity;
import cn.itlaobing.service.UserService;
import cn.itlaobing.vo.JsonResult;
import cn.itlaobing.vo.Status;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by Berlin-IOU on 2017/12/5.
 */
@Controller
@RequestMapping(path = "/users")
public class UserController {
    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;

    @GetMapping()
    public String index(Model model) {
        model.addAttribute("USERS", userService.findAll());
        return "/user/index";
    }

    @GetMapping(path = "/create")
    public String create() {
        return "/user/create";
    }

    @PostMapping(path = "/create")
    public String create(@Valid @ModelAttribute("USER") UserEntity userEntity,
                         BindingResult bindingResult,
                         RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return "/user/create";
        }
        userService.saveOrUpdate(userEntity);
        redirectAttributes.addFlashAttribute("MESSAGE", "添加成功");
        return "redirect:/users";
    }

    @GetMapping(path = "/{id}/update")
    public String update() {
        return "/user/update";
    }


    @DeleteMapping(path = "/{id}")
    @ResponseBody
    public JsonResult<String> destroy(@PathVariable Long id) {
        userService.deleteById(id);
        JsonResult<String> jsonResult = new JsonResult<>(Status.SUCCESS, "删除成功");
        return jsonResult;
    }

    @ModelAttribute
    public void prepareDate(HttpServletRequest request, Model model, @PathVariable(required = false) Long id) {
        model.addAttribute("GENDER", Gender.values());
        if (id != null) {
            model.addAttribute("USER", userService.findById(id));
        } else {
            model.addAttribute("USER", new UserEntity());
        }
    }


    @PutMapping(path = "/{id}/update")
    public String update(@ModelAttribute("USER") UserEntity userEntity, RedirectAttributes redirectAttributes) {
        userService.saveOrUpdate(userEntity);
        redirectAttributes.addFlashAttribute("MESSAGE", "修改成功");
        return "redirect:/users";
    }

}
